package gruppe7.data;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordHash {

    // vi bruger sha-1 til at hashe passwords
    public static final String ALGORITHM = "SHA-1";
    private static MessageDigest digest;
    private static final String hexValues = "0123456789ABCDEF";

    static {
        try {
            digest = MessageDigest.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {

            // vi er garanteret at SHA-1 findes
            e.printStackTrace();
        }
    }

    private static String toHexString(byte[] hashBytes) {
        StringBuilder hb = new StringBuilder(2 * hashBytes.length);

        for (byte b : hashBytes) {
            hb.append(hexValues.charAt((b & 0xF0) >> 4));
            hb.append(hexValues.charAt(b & 0x0F));
        }

        return hb.toString();
    }

    private static String hexHash(String clearText) {
        digest.reset();

        byte[] hashBytes = digest.digest(clearText.getBytes());

        return toHexString(hashBytes);
    }
    private String hash;

    public PasswordHash(String clearText) {
        hash = PasswordHash.hexHash(clearText);
    }

    public String getHash() {
        return hash;
    }
}
